package com.veer.shop.service.impl.admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.veer.shop.config.Constants;
import com.veer.shop.config.ResponseCodeEnum;
import com.veer.shop.mapper.AdminMenuMapper;
import com.veer.shop.mapper.AdminRoleMapper;
import com.veer.shop.param.AdminRoleParam;
import com.veer.shop.param.AdminRoleResult;
import com.veer.shop.pojo.AdminMenu;
import com.veer.shop.pojo.AdminRole;
import com.veer.shop.pojo.ResponseData;
import com.veer.shop.result.ListDataResult;
import com.veer.shop.service.admin.AdminRoleService;
import com.veer.shop.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员角色业务 ServiceImpl
 */
@Service
public class AdminRoleServiceImpl implements AdminRoleService {
	
	@Autowired
	private AdminRoleMapper adminRoleMapper;
	@Autowired
	private ObjectMapper jackJsonMapper;
	@Autowired
	private AdminMenuMapper adminMenuMapper;

	private static final Logger logger = LoggerFactory.getLogger(AdminRoleServiceImpl.class);
	
	@Override
	public ResponseData<?> update(AdminRole adminRole) {
		
		// 校验参数
		Map<String, Object> result = validateAdminRole(adminRole);
		if(!(Boolean)result.get("validated")) {
			return ResponseUtil.error(ResponseCodeEnum.ERROR.getMessage() + result.get("message").toString());
		}
		
		int count = 0;
		if(adminRole.getRoleId() > 0) {
			// 更新管理员用户
			// 检查管理员是否存在
			AdminRole findAdminRole = adminRoleMapper.getById(adminRole.getRoleId());
			if(ObjectUtils.isEmpty(findAdminRole)) {
				// 更新的角色不存在
				return ResponseUtil.error(ResponseCodeEnum.GET_ENTITY_NOT_FOUND.getMessage());
			}
			count = adminRoleMapper.update(adminRole);
		} else {
			// 新增管理员用户
			count = adminRoleMapper.insert(adminRole);
		}
		
		if(count > 0) {
			return ResponseUtil.success();
		}
		return ResponseUtil.error();
	}

	/**
	 * 校验角色信息
	 *
	 * @param adminRole
	 * @return
	 */
	public Map<String, Object> validateAdminRole(AdminRole adminRole) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("validated", false); // 默认校验未通过
		
		// 校验角色名
		if(StringUtils.isEmpty(adminRole.getRoleName())) {
			map.put("message", "角色名不可为空");
			return map;
		}
		map.put("validated", true);
		return map;
	}

	/**
	 * 用户角色列表
	 *
	 * @param adminRoleParam
	 * @return
	 */
	@Override
	public ResponseData<?> getList(AdminRoleParam adminRoleParam) {
		// 列表
		List<AdminRole> adminRoleList = adminRoleMapper.getList(adminRoleParam);
		Page page = PageMethod.startPage(adminRoleParam.getPageNo(), adminRoleParam.getPageSize());
		ListDataResult listDataResult = new ListDataResult();
		List<AdminRoleResult> adminRoleResultList = new ArrayList<AdminRoleResult>();
		for(AdminRole adminRole:adminRoleList) {
			adminRoleResultList.add(this._getAdminRoleResult(adminRole));
		}
		listDataResult.setCount(page.getTotal());
		listDataResult.setList(adminRoleResultList);
		return ResponseUtil.success(listDataResult);
	}

	/**
	 * 删除角色
	 *
	 * @param role_id
	 * @return
	 */
	@Override
	public ResponseData<?> delete(String role_id) {
		String[] roleIds = role_id.split(Constants.SEPARATOR_STRING);
		boolean flag = false;
		for (String id : roleIds) {
			int count = adminRoleMapper.delete(Integer.valueOf(id));
			if(count < 1) {
				flag = true;
				break;
			}
		}
		if(flag)return ResponseUtil.error();
		return ResponseUtil.success();
	}

	/**
	 * 获取角色详情
	 * @param role_id
	 * @return
	 */
	@Override
	public ResponseData<?> get(Integer role_id) {
		AdminRole adminRole = adminRoleMapper.getById(role_id);
		if(adminRole == null)return ResponseUtil.error(ResponseCodeEnum.GET_ENTITY_NOT_FOUND.getMessage());
		AdminRoleResult adminRoleResult = this._getAdminRoleResult(adminRole);
		return ResponseUtil.success(adminRoleResult);
	}

	/**
	 * 获取返回角色实体类
	 *
	 * @param adminRole
	 * @return
	 */
	private AdminRoleResult _getAdminRoleResult(AdminRole adminRole) {
		AdminRoleResult adminRoleResult = new AdminRoleResult();
		adminRoleResult.setRoleId(adminRole.getRoleId());
		adminRoleResult.setRoleName(adminRole.getRoleName());
		adminRoleResult.setIsActived(adminRole.getIsActived());
		adminRoleResult.setIsSystem(adminRole.getIsSystem());
		adminRoleResult.setCreatedAt(adminRole.getCreatedAt());
		adminRoleResult.setUpdatedAt(adminRole.getUpdatedAt());
		adminRoleResult.setOpName(adminRole.getOpName());
		List<Integer> menuIds = new ArrayList<>();
		List<Map<String, Object>> menus = new ArrayList<Map<String, Object>>();
		try {
			menuIds = jackJsonMapper.readValue(adminRole.getMenuId(), List.class);
		} catch (Exception exception) {
			logger.debug("[管理员角色业务]json转换失败：" + exception.getMessage());
		}
		Map<String, Object> map = new HashMap<String, Object>();
		for (int menuId : menuIds) {
			map.put("menu_id", menuId);
			AdminMenu adminMenu = adminMenuMapper.getById(menuId);
			map.put("name", adminMenu.getName());
			menus.add(map);
		}
		adminRoleResult.setMenus(menus);
		return adminRoleResult;
	}
}